package pigshare.profilepicture;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;
import org.primefaces.event.CaptureEvent;


import pigshare.beans.LoginBean;
import pigshare.database.DatabaseConnection;

@RequestScoped
@ManagedBean(name = "photoCamBean")
public class PhotoCamBean {

	private List<String> photos = new ArrayList<String>();
	private Logger log = Logger.getLogger(LoginBean.class);

	private String getRandomImageName() {
		int i = (int) (Math.random() * 10000000);

		return String.valueOf(i);
	}

	public List<String> getPhotos() {
		return photos;
	}

	public void oncapture(CaptureEvent captureEvent) {
		String photo = getRandomImageName();
		this.photos.add(0, photo);
		byte[] data = captureEvent.getData();

		DatabaseConnection con = new DatabaseConnection();
		try {
			// TODO implement WHERE check
			java.sql.PreparedStatement pre = con.getConnection()
					.prepareStatement("UPDATE user SET pic = ?");
			pre.setBytes(1, data);
			pre.executeUpdate();
			pre.close();
			FacesContext
					.getCurrentInstance()
					.addMessage(
							null,
							new FacesMessage(
									"Neues Profilbild",
									String.format("Du hast nun ein Profilbild, dass du mit deiner Cam gemacht hast.")));
			log.info("new profilepictured captured with cam.");
		} catch (SQLException e) {
			e.printStackTrace();
		}

		// ServletContext servletContext = (ServletContext)
		// FacesContext.getCurrentInstance().getExternalContext().getContext();
		// String newFileName = servletContext.getRealPath("") + File.separator
		// + "photocam" + File.separator + photo + ".png";
		//
		// FileImageOutputStream imageOutput;
		// try {
		// imageOutput = new FileImageOutputStream(new File(newFileName));
		// imageOutput.write(data, 0, data.length);
		// imageOutput.close();
		// }
		// catch(Exception e) {
		// throw new FacesException("Error in writing captured image.");
		// }
	}
}
